package com.dosgi;

import java.util.concurrent.locks.ReentrantLock;

import com.dosgi.kit.LockKit;

/**
 * 生命周期管理
 * 
 * @author dingnate
 *
 */
public class DosgiLifeCycle {
	private LifeCycleState state;

	public void waitForInited() throws InterruptedException {
		waitForState(LifeCycleState.INITED);
	}

	public void waitForStarted() throws InterruptedException {
		waitForState(LifeCycleState.STARTED);
	}

	public void waitForClosed() throws InterruptedException {
		waitForState(LifeCycleState.CLOSED);
	}

	/**
	 * @param stateForWait
	 * @throws InterruptedException
	 */
	public void waitForState(LifeCycleState stateForWait) throws InterruptedException {
		if (state != null && stateForWait.ordinal() <= state.ordinal())
			return;
		String name = stateForWait.name();
		ReentrantLock lock = LockKit.lock(name);
		try {
			LockKit.getCondition(name).await();
		} finally {
			lock.unlock();
		}
	}

	public LifeCycleState getState() {
		return state;
	}

	public void setState(LifeCycleState state) {
		this.state = state;
		notifyState(state);
	}

	private void notifyState(LifeCycleState stateToNotify) {
		String name = stateToNotify.name();
		ReentrantLock lock = LockKit.lock(name);
		try {
			LockKit.getCondition(name).signalAll();
		} finally {
			lock.unlock();
		}
	}
}
